<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Yy</title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <!-- //4. 通过上下左右键移动html元素  -->
    <script>
        let box = document.querySelector(".box");
        document.onkeydown = function(e) {
            let code = e.keyCode;
            switch (code) {
                case 37:
                    box.style.left = box.offsetLeft - 5 + "px";
                    break;
                case 38:
                    box.style.top = box.offsetTop - 5 + "px";
                    break;
                case 39:
                    box.style.left = box.offsetLeft + 5 + "px";
                    break;
                case 40:
                    box.style.top = box.offsetTop + 5 + "px";
                    break;
            }
        }
    </script>
</body>

</html>